package com.esd.device.task;

import com.esd.device.entity.Gateway;
import com.esd.device.service.GatewayService;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

@Configuration
public class Tasks {
    @Value("${task.repeatSecond}")
    private Integer repeatSecond ;
    @Autowired
    private GatewayService gatewayService ;

    @PostConstruct
    public void initTask() throws Exception{
        List<Gateway> list = gatewayService.list();
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        if (list != null && !list.isEmpty()) {
            for (Gateway gateway : list) {
                DeviceConstants.LockMap.put(gateway.getServerIp() , new ReentrantLock()) ;
                // 2：定义一个任务调度实例，将该实例与LogJob绑定，任务类需要实现Job接口
                JobDetail job = JobBuilder.newJob(LogJob.class)
                        .withIdentity("job::" + gateway.getServerIp(), "EsdLogGroup") // 定义该实例唯一标识
                        .usingJobData("serverIp", gateway.getServerIp())
                        .build();
                // 3：定义触发器 ，马上执行, 然后每5秒重复执行一次
                Trigger trigger = TriggerBuilder.newTrigger()
                        .withIdentity("trigger::" + gateway.getServerIp(), "EsdLogGroup") // 定义该实例唯一标识
                        .startNow() // 马上执行
                        //.startAt(triggerStartTime) // 针对某个时刻执行
                        .withSchedule(SimpleScheduleBuilder
                                .repeatSecondlyForever(repeatSecond)) // 每2秒执行一次
                        .build();

                // 4：使用触发器调度任务的执行
                scheduler.scheduleJob(job, trigger);
            }

            JobDetail esdLogJob = JobBuilder.newJob(EsdLogJob.class)
                    .withIdentity("job::EsdLogJob", "EsdLogGroup") // 定义该实例唯一标识
                    .build();
            // 3：定义触发器 ，马上执行, 然后每5秒重复执行一次
            Trigger esdLogJobTrigger = TriggerBuilder.newTrigger()
                    .withIdentity("trigger::EsdLogJob", "EsdLogGroup") // 定义该实例唯一标识
                    .startNow() // 马上执行
                    //.startAt(triggerStartTime) // 针对某个时刻执行
                    .withSchedule(SimpleScheduleBuilder
                            .repeatMinutelyForever(10)) // 每10分钟执行一次
                    .build();
            scheduler.scheduleJob(esdLogJob, esdLogJobTrigger);

            scheduler.start();
        }

    }

}
